<template>
  <div class="app-container">
    <el-row :gutter="20" style="width:1375px;">
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="73px">
          <el-form-item label="成果名称" prop="nameKeyword">
            <el-input v-model="queryParams.nameKeyword" placeholder="请输入成果名称"
                      clearable style="width: 200px" @keyup.enter="handleQuery"/>
          </el-form-item>
          
          <el-form-item label="类别" prop="categoryKeyword">
            <el-input v-model="queryParams.categoryKeyword" placeholder="请输入成果类别"
                      clearable style="width: 200px" @keyup.enter="handleQuery"/>
          </el-form-item>

          <el-form-item label="级别" prop="levelKeyword">
            <el-input v-model="queryParams.levelKeyword" placeholder="请输入成果级别"
                      clearable style="width: 200px" @keyup.enter="handleQuery"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd"
              v-hasPermi="['user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="EditPen" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['user:edit']">修改</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['user:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
                  <el-button
                     type="info"
                     plain
                     icon="Upload"
                     @click="handleImport"
                     v-hasPermi="['user:import']"
                  >导入</el-button>
               </el-col>

               <el-col :span="1.5">
                <el-button
                   type="warning"
                   plain
                   icon="Download"
                   @click="handleExport"
                   v-hasPermi="['user:export']"
                >导出</el-button>
             </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="creativeId" label="序号" width="80" />
      <el-table-column prop="username" label="姓名" width="130"/>
      <el-table-column prop="creativeAchievementName" label="成果名称" width="250" />
      <el-table-column prop="creativeCategory" label="类别" width="210" />
      <el-table-column prop="creativeLevel" label="级别" width="150" />
      <el-table-column prop="creativeScore" label="分值" width="100" />
      <el-table-column prop="creativeNotes" label="备注" />
    </el-table>

      <!-- 新增/修改对话框 -->
   <!-- 新增对话框 -->
   <el-dialog :title="dialogTitle" v-model="dialogVisible" width="38%">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="姓名" prop="username" required>
              <el-input v-model="formData.username" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成果名称" prop="creativeAchievementName" required>
              <el-input v-model="formData.creativeAchievementName" placeholder="请输入成果名称" />
            </el-form-item>
          </el-col>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类别" prop="creativeCategory" required>
                <el-input v-model="formData.creativeCategory" placeholder="请输入成果类别" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="级别" prop="creativeLevel" required>
                <el-input v-model="formData.creativeLevel" placeholder="请输入成果级别" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分值" prop="creativeScore" required>
                <el-input-number v-model="formData.creativeScore" :min="0" :step="1" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="creativeNotes">
                <el-input v-model="formData.creativeNotes" type="textarea" placeholder="请填写内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
      </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <!-- <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div> -->
                  <span>仅允许导入xls、xlsx格式文件。</span>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
<!-- 分页组件 -->
<Pagination v-model="queryParams" :total="total" @change="handleChange" />
    <el-footer>

    </el-footer>
  </div>
</template>

<script setup>
import { useUserStore } from '@/store/user.js';
import { ref, onMounted, reactive } from 'vue';
import { getUserCreAchieveList,addUserCreAchieve,updateUserCreAchieve } from "@/api/creativeAchievement";
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from '@/components/Pagination/index.vue';

const tableData = ref([]); // 初始化为响应式数组
const title = ref("");
const open = ref(false);
//处理选中行
const selectedRow = ref(null);

/** 导入按钮操作 */
function handleImport() {
upload.title = "用户导入";
upload.open = true;
};
/*** 用户导入参数 */
const upload = reactive({
// 是否显示弹出层（用户导入）
open: false,
// 弹出层标题（用户导入）
title: "",
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
updateSupport: 0,
// 上传的地址
url: "http://localhost:8080/user/importData",
// headers: {
//   withCredentials: true
// },
// url: import.meta.env.VITE_APP_BASE_API + "/user/importData"
});


// 对话框相关变量
const dialogVisible = ref(false);
const dialogTitle = ref('新增创作成果');
const formData = reactive({
  creativeId: null,
  username: '',
  creativeAchievementName: '',
  creativeCategory: '',
  creativeLevel: '',
  creativeScore: 0,
  creativeNotes: ''
});


// 定义查询参数
const queryParams = ref({
  nameKeyword: '',
  categoryKeyword: '',
  levelKeyword: '',
  currentPage: 1,
  pageSize: 10,
});
const total = ref(0);

// 控制显示/隐藏搜索表单
const showSearch = ref(true);

// 单选和多选状态
const single = ref(false);
const multiple = ref(false);


const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true; // 开始上传时禁用按钮
};


// 查询方法
async function handleQuery() {
  try {
    console.log('查询=',queryParams.value)

    const response = await getUserCreAchieveList({
      ...queryParams.value,
      // userId: currentUserId, // 使用 Pinia 中的用户ID
      currentPage: queryParams.value.currentPage, // 分页从1开始
      pageSize: queryParams.value.pageSize
    });
    tableData.value = response.data; // 更新表格数据
    total.value = response.total; // 总条目数
    console.log('查询结果:', response.data);
  } catch (error) {
    console.error('查询失败:', error);
  }
}

// 重置查询条件
function resetQuery() {
  queryParams.value = {
    userKeyword: ''
  };
  handleQuery(); // 重置后重新查询
}

// 显示新增对话框
function handleAdd() {
  // 清空表单数据
  Object.assign(formData, {
    creativeId: null,
  username: '',
  creativeAchievementName: '',
  creativeCategory: '',
  creativeLevel: '',
  creativeScore: 0,
  creativeNotes: ''
  });
  dialogTitle.value = '新增创作成果';
  dialogVisible.value = true;
}

// 提交表单到后端
async function handleSubmit() {
  try {

    if (formData.creativeId) { // 如果存在id，则为修改操作
      const sendData = {
        creativeId: formData.creativeId,
  username: formData.username,
  creativeAchievementName: formData.creativeAchievementName,
  creativeCategory: formData.creativeCategory,
  creativeLevel: formData.creativeLevel,
  creativeScore: formData.creativeScore,
  creativeNotes: formData.creativeNotes

      };
      await updateUserCreAchieve(sendData);
      ElMessage({
        message: '修改成功',
        type: 'success'
      });
    } else { // 否则为新增操作
      // const sendData = {
      //   username: formData.username,
      //   email: formData.email,
      //   sex: formData.sex,
      //   phone: formData.phone,
      //   address: formData.address,
      //   role: formData.role
      // };
      await addUserCreAchieve(formData);
      ElMessage({
        message: '新增成功',
        type: 'success'
      });
    }

    dialogVisible.value = false; // 关闭对话框
    await handleQuery(); // 刷新列表以显示新添加/修改的记录
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
}

function handleSelectionChange(selection) {
  if (selection.length > 0) {
    single.value = selection.length !== 1;
    multiple.value = false; // 当有选择时，允许删除
    selectedRow.value = selection;
  } else {
    single.value = true;
    multiple.value = true; // 没有选择时，不允许删除
    selectedRow.value = null;
  }
}

//修改
async function handleUpdate() {
  if (!selectedRow.value) {
    ElMessage.error('请选择一条记录进行修改');
    return;
  }
  // 将选中的行数据赋值给formData
  if (selectedRow.value.length > 0) {
    Object.assign(formData, selectedRow.value[0]);
  }

  dialogTitle.value = '修改决策咨询';
  dialogVisible.value = true;
}


const handleChange = (newPage, newPageSize) => {
    queryParams.value.currentPage = newPage;
    queryParams.value.pageSize = newPageSize;
    handleQuery();
};

// 页面加载时自动查询一次
onMounted(() => {
  handleQuery();
});

</script>

<style scoped>
.el-input__inner {
  margin-left: 2px;
}
/* 使用深度选择器 */
:deep(.el-input--small .el-input__inner) {
  height: 30px;
  line-height: 30px;
}
:deep(.el-form-item__label) {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
:deep(.el-form-item) {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}

.demo-date-picker {
display: flex;
width: 100%;
padding: 0;
flex-wrap: wrap;
}

.demo-date-picker .block {
padding: 30px 0;
text-align: center;
border-right: solid 1px var(--el-border-color);
flex: 1;
}

.demo-date-picker .block:last-child {
border-right: none;
}

.demo-date-picker .container {
flex: 1;
border-right: solid 1px var(--el-border-color);
}

.demo-date-picker .container .block {
border-right: none;
}

.demo-date-picker .container .block:last-child {
border-top: solid 1px var(--el-border-color);
}

.demo-date-picker .container:last-child {
border-right: none;
}

.demo-date-picker .demonstration {
display: block;
color: var(--el-text-color-secondary);
font-size: 12px;
margin-bottom: 20px;
}
.el-form--inline .el-form-item{
margin-right: 18px !important;
}
</style>